<?php
// 登录页面
header("content-type:text/html;charset=utf-8");
// 判断是否为POST请求
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 接收传值
    $data = file_get_contents("php://input"); // 解析JSON数据
    $data = json_decode($data, true);
    $uid = $data['u_uid'];
    $pwd = $data['u_pwd'];
    $shenfen = $data['shenfen'];
} else {
    $response = [
        'code' => 400,
        'msg' => '请求方式错误',
    ];
    echo json_encode($response);
    exit();
}


//判断身份
if ($shenfen == '1') {
    $tb = "tb_user";
    $pass = "u_password";
    $l = "u_id"; //用户
}
if ($shenfen == '2') {
    $tb = "tb_repairer";
    $pass = "r_password";
    $l = "r_id"; //维修员
}
if ($shenfen == '3') {
    $tb = "tb_admin";
    $pass = "a_password";
    $l = "a_id"; //管理员
}

//链接数据库
include_once("conn.php");

//查询语句
$sql_select = "SELECT * FROM " . $tb . " WHERE " . $l . " = '" . $uid . "'";
// 执行查询
$result = mysqli_query($conn_DB, $sql_select);
if (!$result) {
    $response = [
        'code' => -2, //数据库查询失败
        'msg' => $sql_select,
    ];
    echo json_encode($response);
    die();
}
$rows = mysqli_num_rows($result);
// 判断查询返回记录是否为空
//如果为空则说明账号不存在
if ($rows == 0) {
    $response = [
        'code' => 0, //账号不存在
    ];
} else {
    $row = mysqli_fetch_array($result);
    // 判断密码是否正确
    if ($row[$pass] == $pwd) {
        // 判断账号状态
        if ($shenfen == '1') {
            if ($row['u_zh_status'] == '0') {
                $response = [
                    'code' => -3, //账号被注销
                    'rtime' => $row['u_revoked'],//注销时间
                ];
                echo json_encode($response);
                die();
            }
        }
        //启用SESSION保存登录信息
        session_start();
        if ($shenfen == '1') {
            $_SESSION['USER'] = $row;
            $url = 'service/user/u-main.php';
        }
        if ($shenfen == '2') {
            $_SESSION['REPAIRER'] = $row;
            $url = 'service/repairer/r-main.php';
        }
        if ($shenfen == '3') {
            $_SESSION['ADMIN'] = $row;
            $url = 'service/administrator/a-main.php';
        }
        $response = [
            'code' => 1, //登录成功
            'url' => $url,//登录成功后跳转的页面
            // 'msg' => $_SESSION['USER'],
        ];
    } else {
        $response = [
            'code' => -1, //密码错误
            'msg' => $sql_select,
        ];
    }
}
// 返回json数据
echo json_encode($response);

// $connect_DB->close();